package com.hzsxy.bighomework.controller;

import com.hzsxy.bighomework.api.*;
import com.hzsxy.bighomework.entity.*;
import com.hzsxy.bighomework.repository.*;
import com.hzsxy.bighomework.service.ClassManagementService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class ClassManagementController {
    @Autowired
    private StudentClassRepository studentClassRepository;
    @Autowired
    private ClassManagementService classManagementService;
    @Autowired
    private ClassInfoRepository classInfoRepository;
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private TeacherRepository teacherRepository;
    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/classManagement")
    public String classManagement(Model model, HttpSession httpSession, @RequestParam("class_id")String class_id){
        List<StudentClassView> views = classManagementService.getStudentClass(class_id);
        model.addAttribute("studentClassList",views);
        return "teacher/class-management";
    }

    @RequestMapping("/classTotal")
    public String classTotal(Model model, HttpSession httpSession){
        String type = (String) httpSession.getAttribute("type");
        List<ClassInfoDO> classes = null;
        if ("student".equals(type)){
            StudentDO studentDO = (StudentDO) httpSession.getAttribute("info");
            List<StudentClassDO> studentClassDOList = studentClassRepository.findByStudentId(studentDO.getStudentId());
            classes = studentClassDOList.stream().map( it -> classInfoRepository.findOne(it.getClassId())).collect(Collectors.toList());
        }else if("admin".equals(type)){
            classes= classInfoRepository.findAll();
        }else{
            Teacher teacher = (Teacher) httpSession.getAttribute("info");
            classes = (List<ClassInfoDO>) classInfoRepository.findAllByTeacher_id(teacher.getTeacher_id());
        }
        model.addAttribute("classes",classes);
        return (type.equals("student")?"student":"teacher")+"/class-total";

    }

    @RequestMapping("/addClassPage")
    public String addClassPage(Model model, HttpSession httpSession){
        return "teacher/class-add";
    }

    @RequestMapping("/studentManagement")
    public String studentManagement(Model model, HttpSession httpSession){
        List<StudentDO> studentDOList = (List<StudentDO>) studentRepository.findAll();
        List<StudentView> views = studentDOList.stream().map(it -> new StudentView(it.getStudentId(),it.getName()))
                .collect(Collectors.toList());
        model.addAttribute("studentInfoList", views);
        return "teacher/student-management";
    }


    @RequestMapping(value ="/studentRemove",method = RequestMethod.GET)
    public String studentRemove(@RequestParam String studentId){
        try{
        List<StudentDO>studentlist=studentRepository.findByStudentId(studentId);
        studentRepository.delete(studentlist);
        return "successful";
        }
        catch (Exception ex){
        ex.printStackTrace();
        return "failed";
        }
    }




    @RequestMapping("/addStudentManualPage")
    public String addStudentManualPage(Model model, HttpSession httpSession){
        return "teacher/student-add-manual";
    }

    @RequestMapping("/selectStudentClass")
    public String selectStudentClass(Model model,@RequestParam String classId){
        List<StudentDO> list = (List<StudentDO>) studentRepository.findAll();
        List<StudentSelectorView> views = list.stream().map(it -> {
            StudentSelectorView view = new StudentSelectorView();
            view.setName(it.getName());
            view.setStudentId(it.getStudentId());
            if (CollectionUtils.isEmpty(studentClassRepository.findByClassIdAndStudentId(classId,it.getStudentId()))){
                view.setSelected(false);
            }else {
                view.setSelected(true);
            }
            return view;
        }).collect(Collectors.toList());
        model.addAttribute("studentList",views);
        model.addAttribute("classId",classId);
        return "teacher/class-student-checkbox";
    }

    @RequestMapping(value = "/addStudentManual",method = RequestMethod.POST)
    @ResponseBody
    public String addStudentManual(SaveStudentRequest saveStudentRequest){
        try{
            StudentDO studentDO = new StudentDO();
            studentDO.setName(saveStudentRequest.getName());
            studentDO.setStudentId(saveStudentRequest.getNumber());
            User user = new User();
            user.setAccount(saveStudentRequest.getNumber());
            user.setPassword("123456");
            user.setType("student");
            user.setStudent_id_fk(studentDO);
            userRepository.save(user);

            return "successful";
        } catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }

    @RequestMapping(value = "/uploadStudentFile",method = RequestMethod.POST)
    @ResponseBody
    public String uploadStudentFile(HttpServletRequest httpServletRequest){
        try{
            MultipartFile file = ((StandardMultipartHttpServletRequest) httpServletRequest).getFile("file");
            String classId=httpServletRequest.getParameter("classId");
            String name=httpServletRequest.getParameter("name");
            String[] splited = name.split("[.]");
            Assert.isTrue("xlsx".equals(splited[splited.length-1]),"只支持excel2007之后的版本，文件后缀为xlsx");
            XSSFWorkbook xssfWorkbook = (XSSFWorkbook) WorkbookFactory.create(file.getInputStream());
            Sheet sheet = xssfWorkbook.getSheetAt(0);
            int totalRow = sheet.getLastRowNum();
            for (int i=1;i<totalRow;i++){
                Row row = sheet.getRow(i);
                String studentId = row.getCell(0).getStringCellValue();
                String studentName = row.getCell(1).getStringCellValue();
                if (StringUtils.isEmpty(studentId) || StringUtils.isEmpty(classId)){
                    continue;
                }
                if (CollectionUtils.isEmpty(studentRepository.findByStudentId(studentId))){
                    StudentDO student = new StudentDO();
                    student.setStudentId(studentId);
                    student.setName(studentName);
                    User user = new User();
                    user.setAccount(studentId);
                    user.setPassword("123456");
                    user.setType("student");
                    user.setStudent_id_fk(student);
                    userRepository.save(user);
                }
                if (CollectionUtils.isEmpty(studentClassRepository.findByClassIdAndStudentId(classId,studentId))){
                    List<ClassInfoDO> classInfoDOList =  classInfoRepository.findByClassId(classId);
                    Assert.isTrue(!CollectionUtils.isEmpty(classInfoDOList),"找不到该课程");
                    ClassInfoDO classInfoDO = classInfoDOList.get(0);
                    classInfoDO.setTotal(classInfoDO.getTotal()+1);
                    Assert.isTrue(classInfoDO.getMax() == -1 || classInfoDO.getMax()<=classInfoDO.getTotal(),"已超过课程人数上限，只有前面部分导入成功");
                    StudentClassDO studentClassDO = new StudentClassDO();
                    studentClassDO.setClassId(classId);
                    studentClassDO.setStudentId(studentId);
                    studentClassRepository.save(studentClassDO);
                    classInfoRepository.save(classInfoDO);
                }
            }
            return "successful";
        } catch (RuntimeException ex){
            ex.printStackTrace();
            return ex.getMessage();
        } catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }


    @RequestMapping("/editClassInfo")
    public String editClassInfo(Model model, HttpSession httpSession, @RequestParam("class_id")String class_id){
        ClassInfoDO classInfoDO =classInfoRepository.findOne(class_id);
        model.addAttribute("classInfoDO", classInfoDO);
        //获取所有老师的数据
        List<Teacher> teachers = (List<Teacher>) teacherRepository.findAll();
        model.addAttribute("teachers",teachers);
        return "teacher/class-edit";
    }

    @GetMapping("/removeClassStudent")
    @ResponseBody
    public String removeClassStudent(Model model, HttpSession httpSession, @RequestParam("class_id")String classId,@RequestParam("student_id")String studentId){
        try {
            List<StudentClassDO> studentClassDOS = studentClassRepository.findByClassIdAndStudentId(classId,studentId);
            studentClassRepository.delete(studentClassDOS);
            List<ClassInfoDO> classInfoDOS =  classInfoRepository.findByClassId(classId);
            Assert.isTrue(!CollectionUtils.isEmpty(classInfoDOS),"找不到该课程");
            ClassInfoDO classInfoDO = classInfoDOS.get(0);
            classInfoDO.setTotal(classInfoDO.getTotal()-1>0 ? classInfoDO.getTotal()-1 : 0);
            classInfoRepository.save(classInfoDO);
            return "successful";
        } catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }

    @PostMapping("/addClass")
    @ResponseBody
    public String addClass(Model model, HttpSession httpSession, SaveClassRequest request){
        try {
            classManagementService.saveClass(request.getNumber(),request.getName(),request.getTeacherId(),request.getMax());
            return "successful";
        } catch (RuntimeException ex){
            ex.printStackTrace();
            return ex.getMessage();
        }catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }

    @PostMapping("/saveStudentClass")
    @ResponseBody
    public String saveStudentClass(Model model, HttpSession httpSession,HttpServletRequest httpServletRequest){
        try {
            String classId = httpServletRequest.getParameter("classId");
            List<String> studentIdList = Arrays.asList(httpServletRequest.getParameterValues("values[]"));
            studentClassRepository.deleteByClassId(classId);
            List<ClassInfoDO> classInfoDOS =  classInfoRepository.findByClassId(classId);
            Assert.isTrue(!CollectionUtils.isEmpty(classInfoDOS),"找不到该课程");
            classInfoDOS.get(0).setTotal(0);
            classInfoRepository.save(classInfoDOS.get(0));
            studentIdList.forEach(it -> {
                List<ClassInfoDO> classInfoDOList =  classInfoRepository.findByClassId(classId);
                ClassInfoDO classInfoDO = classInfoDOList.get(0);
                classInfoDO.setTotal(classInfoDO.getTotal()+1);
                Assert.isTrue(classInfoDO.getMax() == -1 || classInfoDO.getMax()<=classInfoDO.getTotal(),"已超过课程人数上限，只有前面部分导入成功");
                StudentClassDO studentClassDO = new StudentClassDO();
                studentClassDO.setStudentId(it);
                studentClassDO.setClassId(classId);
                studentClassRepository.save(studentClassDO);
                classInfoRepository.save(classInfoDO);
            });
            return "successful";
        } catch (RuntimeException ex){
            ex.printStackTrace();
            return ex.getMessage();
        }catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }

    @RequestMapping("/editClass")
    @ResponseBody
    public String editClass(Model model, HttpSession httpSession,
                            @RequestParam("class_id")String class_id,
                            @RequestParam("class_name")String class_name,
                            @RequestParam("teacher_id")String teacher_id){
        try {
            ClassInfoDO classInfoDO =classInfoRepository.findOne(class_id);
            classInfoDO.setClassName(class_name);
            classInfoDO.setTeacherIdFK(teacherRepository.findOne(teacher_id));
            classInfoRepository.save(classInfoDO);
            return "successful";
        }catch (Exception e){
            e.printStackTrace();
            return "failed";
        }
    }
}
